package algorithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class leetcode_0015 {
    public static void main(String[] args) {
        int[] nums = {0, 0, 0};
        System.out.println(threeSum(nums));
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        if (nums == null || nums.length <= 2) return list;
        int len = nums.length;
        Arrays.sort(nums);
        int l;
        for (int i = 0; i < len - 2; ++i) {
            l = len - 1;

            for (int j = i + 1; j < l; ) {
                if (nums[i] + nums[j] + nums[l] > 0) {
                    l--;
                    while (l > j && nums[l] == nums[l + 1]) l--;
                } else if (nums[i] + nums[j] + nums[l] == 0) {
                    List<Integer> num = new ArrayList<>();
                    num.add(nums[i]);
                    num.add(nums[j]);
                    num.add(nums[l]);
                    list.add(num);
                    j++;
                    while (j<l&&nums[j] == nums[j - 1]) j++;
                    l = len - 1;
                } else {
                    j++;
                    while (j<l&&nums[j] == nums[j - 1]) j++;
                    l = len - 1;
                }
            }
            while (i < len - 2 && nums[i] == nums[i + 1]) ++i;
        }
        return list;
    }
}
